﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using System.Net;
using Entities;

namespace Spider
{
    public class PinterestScraper
    {
        public PinterestUserInfo GetUserInfo(string email)
        {
            var url = GetSearchUrl(email);
            var html = DownloadHtml(url);

            HtmlDocument document = new HtmlDocument();
            document.LoadHtml(html);

            var userInfo = document.DocumentNode.SelectSingleNode("//div[@class='pin user']/a[@class='ImgLink']");
            if(userInfo == null)
                return null;
            var userUrl = userInfo.Attributes["href"].Value;
            var userName = userInfo.SelectSingleNode("//h2");

            var pinterestUserInfo = new PinterestUserInfo();
            pinterestUserInfo.Email = email;
            pinterestUserInfo.Url = userUrl;
            pinterestUserInfo.Name = userName != null ? userName.InnerText : string.Empty;
            SetPinterestInfluence(pinterestUserInfo);
            return pinterestUserInfo;
        }

        public void SetPinterestInfluence(PinterestUserInfo pinterestInfo)
        {
           var url = pinterestInfo.GetAbsoluteUrl();
           var html = DownloadHtml(url);
           HtmlDocument document = new HtmlDocument();
           document.LoadHtml(html);
           var following = document.DocumentNode.SelectSingleNode("//meta[@property='pinterestapp:following']");
           var followers = document.DocumentNode.SelectSingleNode("//meta[@property='pinterestapp:followers']");

           pinterestInfo.Followers = following != null ? long.Parse(following.Attributes["content"].Value) : 0;
           pinterestInfo.Following = followers != null ? long.Parse(followers.Attributes["content"].Value) : 0;
        }

        private string DownloadHtml(string url)
        {
            using (var client = new WebClient())
            {
                try
                {
                    client.Headers.Add("User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");
                    return client.DownloadString(url);
                }
                catch
                {
                    //TODO: log exeption
                    return string.Empty;
                }
            }
        }

        private string GetSearchUrl(string email)
        {
            return string.Format("http://pinterest.com/search/people/?q={0}", email);
        }
    }
}
